package com.msmall.community.dpt.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.common.CascadeCollection;
import com.msmall.community.dpt.dao.SegmentDao;
import com.msmall.community.dpt.model.Segment;
import com.msmall.community.dpt.service.SegmentManager;
import com.msmall.community.user.service.UserManager;

public class SegmentManagerImpl extends BaseManagerImpl<Segment, Long> implements SegmentManager{

	private static final Log log = LogFactory.getLog(SegmentManagerImpl.class);
	
	private SegmentDao segmentDao;
	
	private UserManager userManager;

	public void setSegmentDao(SegmentDao segmentDao) {
		this.segmentDao = segmentDao;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	/**
	 * 创建新的次要栏目
	 * @param userid creator
	 * @return
	 */
	public Segment saveSegment(Segment segment,Long userid) throws Exception{
		try{
			if(segment.getParentid() == null){
				segment.setParentid(ConstantDB.CASCADE_ID_TOP);
			}
			segment.setUserid(userid);
			segment.setCreateTime(new Date());
			segment = (Segment) segmentDao.saveObject(segment);
			return segment;
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
	/**
	 * 刷新所有数据到缓存
	 */
	public void refresh()throws Exception{
		try{
			List<Segment> allDatas = segmentDao.getAll(Segment.class);
			if(allDatas == null || allDatas.size() == 0)
				return;
			CascadeCollection<Segment> cs = new CascadeCollection<Segment>();
			cs.parser(allDatas, "segmentid", "parentid", "orders", CascadeCollection.ORDERS_ASC);
			CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).put(Constants.CACHE_KEY_SEGMENT_CASCADECOLLECTION, cs);
		}catch(Exception e){
			log.debug(e);
			throw e;
		}
	}
}